<?php

class Workset_Db_Table_Row extends Zend_Db_Table_Row implements Workset_Model_Row_Interface {

    protected $_tableInstances = array();

	function addDependentRow($reference, $arFields, $defaults = array()) {
		if ($defaults) {
			$arFields = array_merge($defaults, $arFields);
		}
        $primary = $this->_getPrimaryKey(empty($this->_cleanData));
		$table = $this->_getTableFromString($reference);
		if ($table !== null) {

            $class = $this->getTableClass();
            $ref = $table->getReference($class);
            if ($ref) {
                $foreignKeys = array_combine($ref['columns'], $primary);
                $arFields = array_merge($arFields, $foreignKeys);

			    return $table->insert($arFields);
            }
		}
	}

	function addDependentRows($reference, $arRows, $defaults = array()) {
		foreach ($arRows as $arFields) {
			$this->addDependentRow($reference, $arFields, $defaults);
		}
	}

	function findDependentRow($reference, $ruleKey = null, $select = null) {
        if (is_array($select) || is_string($select)) {
            $where = $select;
            $select = $this->select();

            foreach ((array)$where as $key => $value) {
                if (is_int($key)) {
                    $key = $value;
                    $value = null;
                }
                $select->where($key, $value);
            }
        } elseif ($select === null) {
			$select = $this->select();
		}
		$select->limit(1,0);

		$rowset = $this->findDependentRowset($reference, $ruleKey, $select);
		if ($rowset !== null) {
			return $rowset->current();
		}
	}

    function findDependentRowset($dependentTable, $ruleKey = null, Zend_Db_Table_Select $select = null) {
        if (null !== $select && !($select instanceof Zend_Db_Table_Select)) {
            $where = $select;
            $select = $this->getTable()->select();
            foreach ((array)$where as $key => $value) {
                if (is_int($key))
                    $select->where($value);
                else
                    $select->where($key, $value);
            }
        }
        return parent::findDependentRowset($dependentTable, $ruleKey, $select);
    }

	function getCols() {
		$table = $this->getTable();
		if (null !== $table) {
			return $table->info('cols');
		}
	}

    function getPrimaryKey() {
        return $this->_getPrimaryKey(false);
    }

    function isStored() {
        return !empty($this->_cleanData);
    }

	protected function _getTableFromString($tableName) {
		if (!isset($this->_tableInstances[$tableName])) {
			$table = parent::_getTableFromString($tableName);
			if ($table instanceof Zend_Db_Table_Abstract) {
				$this->_tableInstances[$tableName] = $table;
			} else {
				throw new Zend_Db_Table_Row_Exception("$table is not table object");
			}
		}
		return $this->_tableInstances[$tableName];
	}
}

?>